package com.fujin.gulimall.product.service.impl;

import com.fujin.gulimall.product.Vo.ItemSaleAttrVo;
import com.fujin.gulimall.product.Vo.SkuItemVo;
import com.fujin.gulimall.product.Vo.SpuItemAttrGroupVo;
import com.fujin.gulimall.product.entity.SkuImagesEntity;
import com.fujin.gulimall.product.entity.SpuInfoDescEntity;
import com.fujin.gulimall.product.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fujin.common.utils.PageUtils;
import com.fujin.common.utils.Query;

import com.fujin.gulimall.product.dao.SkuInfoDao;
import com.fujin.gulimall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and(item -> {
                item.eq("sku_id",key).or().like("sku_name",key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)){
            wrapper.ge("price",min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)){
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(new BigDecimal("0")) == 1){
                    wrapper.gt("price",max);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void savaSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    /**
     * //根据spu查询下面所有sku信息
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> getSkuInfoBySpuId(Long spuId) {
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return list;
    }

    @Override
    public SkuItemVo item(Long skuId) {
        SkuItemVo itemVo = new SkuItemVo();

        //使用异步编排
        CompletableFuture<SkuInfoEntity> skuInfoEntityCompletableFuture = CompletableFuture.supplyAsync(() -> {
            //1、查询sku基本信息
            SkuInfoEntity skuInfo = this.baseMapper.selectById(skuId);
            itemVo.setInfo(skuInfo);
            return skuInfo;
        }, executor);


        //3、4、5都是需要第一步返回的结果才能执行的
        CompletableFuture<Void> spuSaleInfo = skuInfoEntityCompletableFuture.thenAcceptAsync((res) -> {
            //3、查询spu销售属性组合
            List<ItemSaleAttrVo> itemSaleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            itemVo.setSaleAttr(itemSaleAttrVos);
        }, executor);

        CompletableFuture<Void> spuInfo = skuInfoEntityCompletableFuture.thenAcceptAsync((res) -> {
            //4、查询spu介绍信息
            SpuInfoDescEntity infoDesc = spuInfoDescService.getById(res.getSpuId());
            itemVo.setDesc(infoDesc);
        }, executor);

        CompletableFuture<Void> spuSpecificationsInfo = skuInfoEntityCompletableFuture.thenAcceptAsync((res) -> {
            //5、查询spu的规格参数
            List<SpuItemAttrGroupVo> groupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            itemVo.setGroupAttrs(groupVos);
        }, executor);

        CompletableFuture<Void> skuImageInfo = CompletableFuture.runAsync(() -> {
            //2、查询sku图片信息
            List<SkuImagesEntity> imagesList = skuImagesService.getImageBySkuId(skuId);
            itemVo.setImages(imagesList);
        }, executor);

        //需要上面所有结束之后才能返回
        try {
            CompletableFuture.allOf(skuInfoEntityCompletableFuture,spuSaleInfo,spuInfo,spuSpecificationsInfo,skuImageInfo).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return itemVo;
    }

}